package com.zy.mc_module.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;

import androidx.core.content.FileProvider;

import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/***
 * 打开相机/拍照工具类
 */
public class CameraUtils {
    private static String TAG = "CameraUtils";
    public static final int GET_IMAGE_BY_CAMERA = 5001;// 拍照
    public static final int GET_IMAGE_BY_PHOTO = 5002;// 相册
    public static final int CROP_IMAGE = 5003;// 裁剪
    public static Uri imageUriFromCamera;// 拍照图片的uri
    public static Uri cropImageUri;// 裁剪图片的uri
    public static String imagePathFromCamera;// 拍照图片的路径
    public static String imageCrop;// 裁剪图片的路径

    /***
     * 打开相机
     */
    public static void openCameraImage(Activity activity) {
        //申请相机权限
        AndPermission.with(activity).runtime().permission(Permission.Group.CAMERA,
                Permission.Group.STORAGE).onGranted(permissions -> {
            //创建拍照的图片uri
            imageUriFromCamera = createCameraImgUri(activity);
            //权限允许,启动相机
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUriFromCamera);
            activity.startActivityForResult(intent, GET_IMAGE_BY_CAMERA);
        }).onDenied(permissions -> {
            ToastUtil.showShort("由于您禁止了使用相机权限,无法进行拍照");
            // 判断用户是不是不再显示权限弹窗了，若不再显示的话进入权限设置页
            if (AndPermission.hasAlwaysDeniedPermission(activity, permissions)) {
                // 打开权限设置页
                AndPermission.with(activity).runtime().setting();
            }
        }).start();
    }

    /***
     * 打开相册
     */
    public static void openLocalImage(Activity activity) {
        try {
            //打开相册
            Intent intent = new Intent(Intent.ACTION_PICK, null);
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            activity.startActivityForResult(intent, CameraUtils.GET_IMAGE_BY_PHOTO);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /***
     * 裁剪图片
     */
    public static void cropImage(Activity activity, Uri srcUri) {
        imageCrop = getPhotoFileName(activity);
        File CropPhoto = new File(imageCrop);
        try {
            if (CropPhoto.exists()) {
                CropPhoto.delete();
            }
            CropPhoto.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //裁剪的图片uri
        cropImageUri = Uri.fromFile(CropPhoto);
        final Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // android7.0设置输出文件的uri
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.setDataAndType(srcUri, "image/*");
        } else {
            intent.setDataAndType(srcUri, "image/*");
        }
        //crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        intent.putExtra("scale", true);//保留比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cropImageUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        activity.startActivityForResult(intent, CROP_IMAGE);
    }

    /***
     * 拍照后的照片的uri
     */
    public static Uri createCameraImgUri(Context context) {
        Uri imageUri;
        File tempFile = null;
        imagePathFromCamera = getPhotoFileName(context);
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            //SD卡的应用关联缓存目录
            tempFile = new File(imagePathFromCamera);
            try {
                if (tempFile.exists()) {
                    tempFile.delete();
                }
                tempFile.createNewFile();
            } catch (Exception e) {
                ToastUtil.showShort("没有找到储存目录");
            }
        } else {
            ToastUtil.showShort("没有储存卡");
        }

        if (Build.VERSION.SDK_INT >= 24) {
            /**
             * 从Android7.0开始，直接使用本地的真是路径的URI被认为是不安全的，会抛出FileUriExposeException
             * 而FileProvider是一种特殊的ContentProvider，可以给外部选择性的分享Uri，提高安全性*/
            imageUri = FileProvider.getUriForFile(context, "com.whpp.swy_kt.FileProvider", tempFile);
        } else {
            imageUri = Uri.fromFile(tempFile);
        }
        return imageUri;
    }

    /***
     * 使用系统当前日期加以调整作为照片的名称
     */
    public static String getPhotoFileName(Context context) {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        if (Build.VERSION.SDK_INT >= 30) {
            //android 11以上，将文件创建在公有目录
            String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath();
            return path + "/" + dateFormat.format(date) + "swyimg.jpg";
        } else {
            return context.getExternalCacheDir() + "/" + dateFormat.format(date) + "swyimg.jpg";
        }
    }

    /**
     * 读取图片的旋转的角度
     *
     * @param path 图片绝对路径
     * @return 图片的旋转角度
     */
    public static int getBitmapDegree(String path) {
        int degree = 0;
        try {
            // 从指定路径下读取图片，并获取其EXIF信息
            ExifInterface exifInterface = new ExifInterface(path);
            // 获取图片的旋转信息
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    /**
     * 将图片按照某个角度进行旋转
     *
     * @param bm     需要旋转的图片
     * @param degree 旋转角度
     * @return 旋转后的图片
     */
    public static Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
        Bitmap returnBm = null;
        if (degree == 0) {
            //没有旋转直接返回
            return bm;
        } else {
            // 根据旋转角度，生成旋转矩阵
            Matrix matrix = new Matrix();
            matrix.postRotate(degree);
            try {
                // 将原始图片按照旋转矩阵进行旋转，并得到新的图片
                returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
            } catch (OutOfMemoryError e) {
            }
            if (returnBm == null) {
                returnBm = bm;
            }
            if (bm != returnBm) {
                bm.recycle();
            }
            return returnBm;
        }
    }
}
